package com.base.api.emr.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.base.api.emr.IHisCaseRecordService;
import com.base.dao.emr.HisCaseRecordMapper;
import com.base.dao.emr.SdeLobMedicalrecordMapper;
import com.base.vo.emr.HisCaseRecord;
import com.base.vo.emr.SdeLobMedicalrecord;
import com.cenboomh.mr.parser.DiseaseDocParser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class HisCaseRecordServiceImpl implements IHisCaseRecordService {

    @Autowired
    private HisCaseRecordMapper hisCaseRecordMapper;

    @Autowired
    private SdeLobMedicalrecordMapper sdeLobMedicalrecordMapper;

    /**
     * 查询全部
     *
     * @return
     */
    @Override
    public List<HisCaseRecord> findAll() {

        return hisCaseRecordMapper.selectAll();
    }

    /**
     * 根据住院号查询记录
     *
     * @param patientId
     * @return
     */
    @Override
    public String queryRecordByPatientId(String patientId) {
        Map<String, Object> map = new HashMap<>();
        List<HisCaseRecord> list;
        if (patientId == null) {
            list = new ArrayList<>();
        } else {
            list = hisCaseRecordMapper.selectByPid(patientId);
        }
        map.put("code", "0");
        map.put("data", list);
        return JSONArray.toJSONString(map);
    }

    /**
     * 根据主键查询病历XML信息
     *
     * @param id
     * @return
     */
    @Override
    public String parseXmlById(Integer id) {
        Map<String, Object> map = new HashMap<>();
        HisCaseRecord hisCaseRecord = null;
        String result = null;
        if (id != null) {
            hisCaseRecord = hisCaseRecordMapper.selectByPrimaryKey(id);
            try {
                result = new String(hisCaseRecord.getHtmlContent(), "UTF-8");
            } catch (Exception e) {

            }


        }
        map.put("code", "0");
        map.put("data", result);
        return JSON.toJSONString(map);
    }

    /**
     * 修改病历内容
     *
     * @param docLobId
     * @param xmlText
     * @return
     */
    @Override
    public String saveMedicalRecordXml(String docLobId, String xmlText) {
        Map<String, Object> map = new HashMap<>();
        map.put("code", "0");
        map.put("data", "");
        try {
            SdeLobMedicalrecord sdeLobMedicalrecord = new SdeLobMedicalrecord();
            sdeLobMedicalrecord.setLobId(docLobId);
            sdeLobMedicalrecord.setLobContent(xmlText.getBytes());
            sdeLobMedicalrecordMapper.updateSelective(sdeLobMedicalrecord);
        } catch (Exception e) {
            map.put("code", "400");
            map.put("data", e.getMessage());
        }
        return JSON.toJSONString(map);
    }

    /**
     * 通过主键查询病历文本信息
     *
     * @param id
     * @return
     */
    @Override
    public String parseTextById(Integer id) {
        Map<String, Object> map = new HashMap<>();
        HisCaseRecord hisCaseRecord = hisCaseRecordMapper.selectByPrimaryKey(id);
        if (hisCaseRecord == null) {
            map.put("code", "100");
            map.put("msg", "根据主键[" + String.valueOf(id) + "]查询后台数据为空，请检查！");
        } else {

            DiseaseDocParser parser = null;
            try {

                parser = new DiseaseDocParser(new String(hisCaseRecord.getHtmlContent(), "UTF-8"));

                // 获取整个文档的Map结构
                Map<String, Object> documentMap = parser.getDocumentMap();

                StringBuilder result = new StringBuilder("");
                try {
                    for (Map.Entry<String, Object> entry : documentMap.entrySet()) {
                        if (!"header".equals(entry.getKey()) && !"footer".equals(entry.getKey())) {
                            Map<String, String> map1 = (Map<String, String>) entry.getValue();
                            result.append("【" + map1.get("_displayName") + "】 ").append(map1.get("_text") == null ? map1.get("_value") : map1.get("_text") + "\n");
                        }
                    }
                } catch (Exception e) {

                } finally {
                    documentMap.clear();
                }

                map.put("code", "0");
                map.put("data", result.toString());
            } catch (UnsupportedEncodingException e) {
                map.put("code", "100");
                map.put("msg", e.toString());
            }
            // 获取整个文档的Map结构

        }
        return JSONArray.toJSONString(map);
    }


    public String parse(DiseaseDocParser parser, String path) {
        List<Object> list = (List<Object>) parser.get("$..*[?(@._displayName=='" + path + "' && @._text)]");
        if (!list.isEmpty()) {
            Map<String, String> map = (Map<String, String>) list.get(0);
            return map.get("_text");
        } else {
            return null;
        }
//        Map<String, String> map = (Map<String, String>) parser.get("$..*[?(@._displayName=='" + path + "' && @._text)]");
//        if(map!=null){
//            return map.get("_text");
//        }else {
//           return null;
//       }
    }

    /**
     * 通过主键查询病历信息并返回解析结果
     *
     * @param id
     * @return
     */
    @Override
    public String parseById(Integer id) {
        Map<String, Object> map = new HashMap<>();
        HisCaseRecord hisCaseRecord = hisCaseRecordMapper.selectByPrimaryKey(id);
        if (hisCaseRecord == null) {
            map.put("code", "100");
            map.put("msg", "根据主键[" + String.valueOf(id) + "]查询后台数据为空，请检查！");
        } else {
            DiseaseDocParser parser = null;
            try {
                parser = new DiseaseDocParser(new String(hisCaseRecord.getHtmlContent(), "UTF-8"));
                // 获取整个文档的Map结构
                Map<String, Object> documentMap = parser.getDocumentMap();
                map.put("code", "0");
                map.put("data", documentMap);
            } catch (UnsupportedEncodingException e) {
                map.put("code", "100");
                map.put("msg", e.toString());
            }

        }
        return JSONArray.toJSONString(map);
    }


}
